package com.cnd.scm.datasource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
import org.springframework.jdbc.datasource.init.DatabasePopulator;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * @version V1.0
 * @ClassName: DBInitializerConfig
 * @Description: 数据库初始化时
 * @author: 李启联
 * @date: 2020-05-20 16:41
 * @Copyright: Copyright (c), 2020
 */
@Configuration
@EnableTransactionManagement
public class DBInitializerConfig {

    @Bean
    public DataSourceInitializer dataSourceInitializer(DataSource dataSource) throws IOException {
        final DataSourceInitializer initializer = new DataSourceInitializer();
        initializer.setDataSource(dataSource);
        initializer.setDatabasePopulator(databasePopulator());
        initializer.setEnabled(true);
        return initializer;
    }

    private DatabasePopulator databasePopulator() throws IOException {
        ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
        resourceDatabasePopulator.setContinueOnError(false);
        resourceDatabasePopulator.addScripts(
                new PathMatchingResourcePatternResolver().getResources("classpath*:/sqlscript/mysql/Search(MySql).sql")
        );
        return resourceDatabasePopulator;
    }
}